package com.example.websocket.controller;

import com.example.websocket.model.MessageStore;
import com.example.websocket.security.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RestController
@RequiredArgsConstructor
public class ChatController {

    private final SimpMessagingTemplate messagingTemplate;
    private final MessageStore messageStore;
    private final JwtTokenUtil jwtTokenUtil;

    @PostMapping("/api/login")
    public String login(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        return jwtTokenUtil.generateToken(username);
    }

    @MessageMapping("/chat.private")
    public void handlePrivateMessage(@Payload String message, SimpMessageHeaderAccessor headerAccessor) {
        String sender = headerAccessor.getUser().getName();
        String recipient = headerAccessor.getFirstNativeHeader("recipient");
        
        if (recipient != null) {
            // 存储消息
            messageStore.storeMessage(sender, message);
            
            // 构建消息内容
            String messageContent = String.format("来自 %s 的消息: %s", sender, message);
            
            // 发送给指定用户
            messagingTemplate.convertAndSendToUser(
                recipient,
                "/queue/messages",
                messageContent
            );
        }
    }

    @MessageMapping("/chat.get")
    public void getStoredMessage(SimpMessageHeaderAccessor headerAccessor) {
        String userId = headerAccessor.getUser().getName();
        String storedMessage = messageStore.getMessage(userId);
        
        if (storedMessage != null) {
            messagingTemplate.convertAndSendToUser(
                userId,
                "/queue/messages",
                "存储的消息: " + storedMessage
            );
            // 获取后删除消息
            messageStore.removeMessage(userId);
        }
    }
} 